//
//  PersonCertV2ViewController.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/11/8.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "PersonCertV2ViewController.h"

@interface PersonCertV2ViewController ()

/// 模型视图
@property (nonatomic, readonly, strong) PersonCertV2ViewModel* viewModel;

// UI
//@property (weak, nonatomic) UILabel *addressLabel;

//IBOutlet
@property (weak, nonatomic) IBOutlet UITextField* phoneTF;
@property (weak, nonatomic) IBOutlet UITextField* pwdTF;
@property (weak, nonatomic) IBOutlet UITextField* vercodeTF;
@property (weak, nonatomic) IBOutlet UIButton* vercodeBtn;
@property (weak, nonatomic) IBOutlet UIButton* submitBtn;

@end

@implementation PersonCertV2ViewController
@dynamic viewModel;

- (instancetype)initWithViewModel:(SUViewModel2 *)viewModel
{
    self = [super initWithViewModel:viewModel];
    if (self)
    {
        [self initData];
        [self initLoadForRAC];
        [self initUI];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    if (self.viewModel.isBack2Dismiss)
    {
        UIButton* backBtn = self.navigationItem.leftBarButtonItem.customView;
        [backBtn removeAllTargets];
        [backBtn addTarget:self action:@selector(_onBtnBack) forControlEvents:UIControlEventTouchUpInside];
    }
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    NSLog(@"viewDidLayoutSubviews");
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initData
{
    
}

- (void)initLoadForRAC
{
    @weakify(self)
    [[self rac_signalForSelector:@selector(viewDidLoad)] subscribeNext:^(id x)
     {
         @strongify(self)
         
     }];
}

- (void)initUI
{
    @weakify(self);
    
}

- (void)bindViewModel
{
    [super bindViewModel];
    
    @weakify(self)
    
    RACSignal* willAppearSignal = [[self rac_signalForSelector:@selector(viewWillAppear:)] replay];
    RACSignal* willDisAppearSignal = [[self rac_signalForSelector:@selector(viewWillDisappear:)] replay];
    RACSignal* didAppearSignal = [[self rac_signalForSelector:@selector(viewDidAppear:)] replay];
    RACSignal* viewDidLayoutSVSignal = [[self rac_signalForSelector:@selector(viewDidLayoutSubviews)] replay];
    
    [willAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
    }];
    
    [willDisAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
    }];
    
    [didAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
        NSLog(@"viewDidAppear");
        
        // ScrollView 内容 未能在此时才约束
        
        //Request
        
    }];
    
    [[self rac_signalForSelector:@selector(viewWillDisappear:)] subscribeNext:^(id x)
     {
         @strongify(self)
         
     }];
    
    [[[[viewDidLayoutSVSignal take:1] zipWith:[willAppearSignal replay]] deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self)
         
         //重置 更新 frame
         [self _setupAllView];
     }];
    
#pragma mark -- bindViewModel
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    RAC(self.viewModel, strPhone) = [self.phoneTF rac_textSignal];
    RAC(self.viewModel, strPwd) = [self.pwdTF rac_textSignal];
    RAC(self.viewModel, strVercode) = [self.vercodeTF rac_textSignal];
    
    DataManager* dm = [DataManager sharedDataManager];
    [[[RACObserve(dm.phoneVCodeCaler, verCodeTime) deliverOnMainThread] map:^id(id value) {
        @strongify(self)
        
        int waitTime = [value intValue];
        
        if (waitTime > 0)
        {
            self.vercodeBtn.userInteractionEnabled = NO;
            
            return [NSString stringWithFormat:@"%ds", waitTime];
        }
        else
        {
            self.vercodeBtn.userInteractionEnabled = YES;
            
            return @"获取验证码";
        }
    }] subscribeNext:^(id x) {
        @strongify(self)
        
        NSString* str = x;
        
        self.vercodeBtn.titleLabel.text = str;
        
        [self.vercodeBtn setTitle:str forState:UIControlStateNormal];
    }];
    
    [[[[self.vercodeBtn rac_signalForControlEvents:UIControlEventTouchUpInside] deliverOnMainThread]
      doNext:^(id x) {
          @strongify(self);
          [self.view endEditing:YES];
          [MBProgressHUD mh_showProgressHUD:[NSString stringWithFormat:@"%@....", @"获取验证码"]];
      }]
     subscribeNext:^(UIButton *sender) {
         @strongify(self);
         [self.viewModel.verCodeCommand execute:nil];
     }];
    
    // 验证码
    /// 数据成功
    [[self.viewModel.verCodeCommand.executionSignals.switchToLatest deliverOnMainThread]
     subscribeNext:^(id x) {
         @strongify(self);
         [MBProgressHUD mh_hideHUD];
         
         [MBProgressHUD mh_showTips:x];
     }];
    
    /// 错误信息
    [self.viewModel.verCodeCommand.errors subscribeNext:^(NSError *error) {
        /// 处理验证错误的error
        if ([error.domain isEqualToString:SUCommandErrorDomain]) {
            [MBProgressHUD mh_showTips:error.userInfo[SUCommandErrorUserInfoKey]];
            return ;
        }
        [MBProgressHUD mh_showErrorTips:error];
    }];
    
    [[self.submitBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        
        [self.view resignFirstResponder];
        
        [MBProgressHUD mh_showProgressHUD:@"绑定中..."];
        
        [self.viewModel.submitCommand execute:nil];
    }];
    [[self.viewModel.submitCommand.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self);
         
         [MBProgressHUD mh_hideHUD];
         
         [MBProgressHUD mh_showTips:x];
         
         if (self.viewModel.isBack2Dismiss)
         {
             [self dismissViewControllerAnimated:YES completion:^{
                 
             }];
         }
         else
         {
             [self.navigationController popViewControllerAnimated:YES];
         }
         
         UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
         [um updateUserInfo];
     }];
    [[self.viewModel.submitCommand.errors deliverOnMainThread] subscribeNext:^(NSError* error)
     {
         @strongify(self);
         
         [MBProgressHUD mh_hideHUD];
         
         if ([error.domain isEqualToString:SUCommandErrorDomain])
         {
             [MBProgressHUD mh_showTips:error.userInfo[SUCommandErrorUserInfoKey]];
             return;
         }
         [MBProgressHUD mh_showErrorTips:error];
     }];
}

- (void)_setupAllView
{
    @weakify(self);
    
}

#pragma mark - 功能
- (void)_onBtnBack
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark - 跳转

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
